package com.teleinfo.barcode_scan_plugin;

import android.app.Activity;
import android.content.Intent;

import io.flutter.Log;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;

import static android.app.Activity.RESULT_OK;

/** BarcodeScanPlugin */
public class BarcodeScanPlugin  implements MethodCallHandler, PluginRegistry.ActivityResultListener  {
  Activity activity;

  public BarcodeScanPlugin(Activity activity) {
    this.activity = activity;
  }

  Result result;
  /** Plugin registration. */
  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "barcode_scan_plugin");
    BarcodeScanPlugin plugin = new BarcodeScanPlugin(registrar.activity());
    channel.setMethodCallHandler(plugin);
    registrar.addActivityResultListener(plugin);
  }

  @Override
  public void onMethodCall(MethodCall call, Result result) {
    if (call.method.equals("getPlatformVersion")) {
      Log.e("scan", "go into getPlatformVersion...");
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("scan")) {
      this.result = result;
      Log.e("scan", "go into scan...");
      //调起barcode
      showBarcodeView();
    } else {
      Log.e("scan", "go into xxx...");
      result.notImplemented();
    }
  }

  void showBarcodeView() {
    Intent intent = new Intent(activity, ScanActivity.class);
    activity.startActivityForResult(intent, 100);
  }

  @Override
  public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
      if (resultCode == RESULT_OK) {
        String barcode = data.getStringExtra("SCAN_RESULT");
        if(barcode == null) return false;
        this.result.success(barcode);
      } else {
        if(data!= null){
          String barcode = data.getStringExtra("ERROR_CODE");
          this.result.error(barcode, null, null);
        }
      }
      return true;
    }
    return false;
  }
}
